<?php
/**
 * Created by PhpStorm.
 * User: LENOVO
 * Date: 2020/10/5
 * Time: 22:06
 */
namespace app\admin\controller\small;

use app\common\controller\Backend;
use app\Request;
use think\Exception;
use app\common\model\Product;
use app\common\model\ProductDetails;
use app\common\model\ProductSku;
use think\facade\Db;
class Goods extends Backend
{
    protected $model = null;
    protected $skuModel = null;
    public function initialize(){
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new Product();
        $this->skuModel = new ProductSku();
        //所属分类
//        $cate = (new Category)->where('status', 1)->order('createtime', 'desc')->select();
//        $category = [0 => __('None')];
//        foreach ($cate as $k => $v) {
//            $category[$v['id']] = $v['cate_name'];
//        }
//        //所属店铺
//        $shops = (new Shops) -> where('status',1) -> order('createtime asc') -> select();
//        $shopslist =[0 => __('None')];
//        foreach ($shops as $k => $v) {
//            $shopslist[$v['id']] = $v['title'];
//        }
//        $this -> assign('shopslist',$shopslist);
//        $this->assign('category', $category);
    }

    public function index (Request $request){
        if ($request->isAjax()) {
            if ($request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $total = $this->model
                ->where($where)
//                ->where('status', 1)
                ->count();
            $list = $this->model
                ->where($where)
//                ->where('status', 1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = ['total' => $total, 'rows' => $list];
            return json($result);
        }
        return $this-> fetch();
    }

    /**
     * 商品添加
     * @return string
     * @throws \Exception
     */
    public function add(){
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if($params){
                $skus = $this->request->post('rowsku/a');
                $details = $this->request->post('details/a');
                try {
//                    if($skus['skutitle'][0] != '' ){
//                        $pos = array_search(min($skus['skuprice']), $skus['skuprice']);
//                        $params['price'] = $skus['skuprice'][$pos];
//                        $params['stock'] = array_sum($skus['skustock']);
//                    }
                    $params['images'] = explode(',',$details['images_url'])[0];
                    $params['createtime'] = time();
                    $this->model->save($params);
                    $details['productid'] = $this->model->id;
                    $details['createtime'] = time();
                    if($skus['skuprice'][0] != ''){
                        $this->getSkuInfo($skus['skuid'],$skus['skutitle'], $skus['skuprice'], $skus['skustock'], $this->model->id);
                    }
                    (new ProductDetails) -> save($details);
                    $this->success();
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error();
        }
        return $this-> fetch();
    }

//修改sku信息
    public function getSkuInfo ($skuids,$skuTitle, $skuPrice, $skuStock, $pid) {
        $savenumber=0;
        foreach ($skuids as $k => $v){
            $sku = [
                'product_id'=>$pid,
                'skutitle'=>$skuTitle[$k],
                'skuprice'=>$skuPrice[$k],
                'skustock'=>$skuStock[$k],
                'createtime' => time()
            ];
            if($v == 0){
                $this->skuModel-> insert($sku);
            }else{
                $savenumber += $this->skuModel->where('id', $v)->update($sku);
            }
        }
    }
    /**
     * 商品修改
     * @param null $ids
     * @return string
     * @throws \Exception
     */
    public function edit ($ids = null){
        $product = $this->model->find($ids);
        //sku属性
        $sku = $product->skus()->select();
        $details = (new ProductDetails)  ->  where('productid',$ids) -> find() ;
        $this->assign('details', $details);
        $this->assign('sku', $sku);
        if (! $product) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            $skus = $this->request->post('rowsku/a');
            $details = $this->request->post('details/a');
            try {
                if(!empty($skus['skuprice'])){
                    $pos = array_search(min($skus['skuprice']), $skus['skuprice']);
                    $params['price'] = $skus['skuprice'][$pos];
                    $params['stock'] = array_sum($skus['skustock']);
                }
                $params['images'] = explode(',',$details['images_url'])[0];
                $params['updatetime'] = time();
                $product->save($params);
                if(!empty($skus['skuprice'])){
                    $this->getSkuInfo($skus['skuid'],$skus['skutitle'], $skus['skuprice'], $skus['skustock'], $ids);
                }
                (new ProductDetails) -> where('productid',$ids) -> update($details);
                $this->success();
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $this->assign('row', $product);
        return $this->fetch();
    }



    /**
     * 删除类目
     * @param string $ids
     * @throws \Exception
     */
    public function del ($ids = '')
    {
        if ($ids) {
            $this->model->destroy($ids);
            (new ProductDetails) -> whereIn("productid",$ids) -> delete();
            $this->success();
        }
        $this->error();
    }
}
